<template>
  <div class="app-container">
    <el-form ref="form" :model="queryParam" :inline="true">
      <el-form-item prop="module" label="module" :label-width="formLabelWidth">
        <el-input v-model="queryParam.module" placeholder="module" type="input">
        </el-input>
      </el-form-item>
      <el-form-item prop="operate" label="operate" :label-width="formLabelWidth">
        <el-input v-model="queryParam.operate" placeholder="operate" type="select">
        </el-input>
      </el-form-item>
      <el-form-item prop="route" label="route" :label-width="formLabelWidth">
        <el-input v-model="queryParam.route" placeholder="route" type="upload">
        </el-input>
      </el-form-item>
      <el-form-item prop="params" label="params" :label-width="formLabelWidth">
        <el-input v-model="queryParam.params" placeholder="params" type="upload">
        </el-input>
      </el-form-item>
      <el-form-item prop="ip" label="ip" :label-width="formLabelWidth">
        <el-input v-model="queryParam.ip" placeholder="ip" type="input">
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" type="primary" @click="handleSearch">查询</el-button>
      </el-form-item>
    </el-form>
    <el-divider content-position="center">
    </el-divider>
    <div class="filter-container">
      <el-row>
        <el-col :span="12">
          <div class="grid-content">
            <el-button class="filter-item" icon="el-icon-refresh" @click="handleRefresh">刷新</el-button>
            <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate()">添加</el-button>
            <el-button v-if="this.selectedIds.length" size="small" class="filter-item mb-5" type="danger" icon="el-icon-delete" @click="handleMultiDelete">批量删除</el-button>
            <el-button @click="clearFilter">清除所有过滤器</el-button>
          </div>
        </el-col>
        <el-col :span="12">
          <el-button icon="el-icon-info" circle @click="templateVersion" style="float: right; padding: 3px 0">
          </el-button>
          <el-dropdown @command="handleTableCommand" style="float: right; padding: 3px 0">
            <span class="el-dropdown-link">
              <i class="el-icon-more el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="a">配置表格</el-dropdown-item>
              <el-dropdown-item command="b" divided>移除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <div class="grid-content">
            <el-dropdown @command="handleDropdownCommand" style="float: right; padding: 3px 0">
              <span class="el-dropdown-link">
                <i class="el-icon-menu el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-checkbox-group v-model="checkList">
                  <el-dropdown-item command="a">
                    <el-checkbox label="module">
                    </el-checkbox>
                  </el-dropdown-item>
                  <el-dropdown-item command="a">
                    <el-checkbox label="operate">
                    </el-checkbox>
                  </el-dropdown-item>
                  <el-dropdown-item command="a">
                    <el-checkbox label="route">
                    </el-checkbox>
                  </el-dropdown-item>
                  <el-dropdown-item command="a">
                    <el-checkbox label="params">
                    </el-checkbox>
                  </el-dropdown-item>
                  <el-dropdown-item command="a">
                    <el-checkbox label="ip">
                    </el-checkbox>
                  </el-dropdown-item>
                </el-checkbox-group>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-table ref="multipleTable" :data="data" tooltip-effect="dark" style="width: 100%" fit @selection-change="handleSelectMulti">
      <el-table-column type="selection" width="55" v-if="true">
      </el-table-column>
      <el-table-column prop="module" label="module" show-overflow-tooltip v-if="true">
      </el-table-column>
      <el-table-column prop="operate" label="operate" show-overflow-tooltip v-if="true">
      </el-table-column>
      <el-table-column prop="route" label="route" show-overflow-tooltip v-if="true">
      </el-table-column>
      <el-table-column prop="params" label="params" show-overflow-tooltip v-if="true">
      </el-table-column>
      <el-table-column prop="ip" label="ip" show-overflow-tooltip v-if="true">
      </el-table-column>
      <el-table-column prop="creator" label="创建人" v-if="true">
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" v-if="true">
      </el-table-column>
      <el-table-column prop="updated_at" label="更新时间" v-if="true">
      </el-table-column>
      <el-table-column label="操作" v-if="true" fixed="right">
        <template slot-scope="module">
          <el-button type="primary" icon="el-icon-edit" @click="handleUpdate(module.row)">
          </el-button>
          <el-button type="danger" icon="el-icon-delete" @click="handleDelete(module.row.id)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="paginate.current" hide-on-single-page :page-sizes="paginate.sizes" :page-size="paginate.limit" :layout="paginate.layout" :total="paginate.total">
    </el-pagination>
    <!----------------------------------- 新增/编辑 ---------------------------------------------->
    <el-drawer ref="drawer" size="60%" :title="drawerTitle" :visible.sync="formVisible" :before-close="handleClose" direction="rtl" @close="handleCancel">
      <div class="demo-drawer__content">
        <el-form :ref="formName" :model="formFieldsData" :rules="rules">
          <el-form-item prop="module" label="module" :label-width="formLabelWidth">
            <template>
              <el-input v-model="formFieldsData.module" placeholder="module" type="text" autocomplete="off" clearable>
              </el-input>
            </template>
          </el-form-item>
          <el-form-item prop="operate" label="operate" :label-width="formLabelWidth">
            <template>
              <el-cascader
                      size="small"
                      :options="operateOption"
                      v-model="selectedoperateOptions"
                      @change="handleoperateChange">
              </el-cascader>
            </template>
          </el-form-item>
          <el-form-item prop="route" label="route" :label-width="formLabelWidth">
            <template>
              <el-upload class="uploader" ref="routeupload" :action="imageAction" :show-file-list="true" :headers="headers" multiple :limit="5" :on-exceed="handlerouteExceed" :on-success="handlerouteSuccess" :on-remove="handlerouteRemove" :before-upload="beforerouteUpload" :file-list="routefileList" :auto-upload="false">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitrouteUpload">上传到服务器</el-button>
                <div slot="tip" class="el-upload__tip">good</div>
              </el-upload>
            </template>
          </el-form-item>
          <el-form-item prop="params" label="params" :label-width="formLabelWidth">
            <template>
              <el-upload class="uploader" ref="paramsupload" :action="imageAction" :show-file-list="true" :headers="headers" multiple :limit="5" :on-exceed="handleparamsExceed" :on-success="handleparamsSuccess" :on-remove="handleparamsRemove" :before-upload="beforeparamsUpload" :file-list="paramsfileList" :auto-upload="false">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitparamsUpload">上传到服务器</el-button>
                <div slot="tip" class="el-upload__tip">上传提示</div>
              </el-upload>
            </template>
          </el-form-item>
          <el-form-item prop="ip" label="ip" :label-width="formLabelWidth">
            <template>
              <el-input v-model="formFieldsData.ip" placeholder="ip" type="text" autocomplete="off" clearable>
              </el-input>
            </template>
          </el-form-item>
        </el-form>
        <div slot="footer" class="drawer__footer">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
  import {getToken} from '@/utils/auth';
  import formOperate from '@/layout/mixin/formOperate';
  import { provinceAndCityData, regionData, provinceAndCityDataPlus, regionDataPlus, CodeToText, TextToCode } from 'element-china-area-data';

  export default {
    name: 'example_test',
    mixins: [formOperate],
    data () {
      return {
        url: 'test',
        formName: 'test',
        formLabelWidth: '120px',
        queryParam: {
          module:'',operate:'',route:'',params:'',ip:'',
        },
        formVisible: false,
        formFieldsData: {
          module:'',operate:'',route:'',params:'',ip:'',
        },
        loading: false,
        checkList: [],
        search: '',
        drawerTitle: 'test',
        form: {
          module:'',operate:'',route:'',params:'',ip:'',
        },
        timer: null,
        rules: {},
        operateOptionList: [],
        headers: {
          authorization: 'Bearer ' + getToken()
        },
        imageAction: process.env.VUE_APP_BASE_API + '/upload/image',
        fileAction: process.env.VUE_APP_BASE_API + '/upload/file',
        operateOption: regionData,
        selectedoperateOptions: []
      };
    },
    computed: {
      routefileList: {
        get: function () {
          if (this.formFieldsData.route) {
            return JSON.parse(this.formFieldsData.route);
          } else {
            return [];
          }
        },
        set: function (newValue) {
        }
      },
      paramsfileList: {
        get: function () {
          if (this.formFieldsData.params) {
            return JSON.parse(this.formFieldsData.params);
          } else {
            return [];
          }
        },
        set: function (newValue) {
        }
      }
    },
    watch: {
      formFieldsData: {
        handler(data) {
          if (data.operate) {
            let region = data.operate.split(',');
            let province = region[0];
            let city = region[1];
            let area = region[2];
            this.selectedoperateOptions[0] = TextToCode[province].code;
            this.selectedoperateOptions[1] = TextToCode[province][city].code;
            this.selectedoperateOptions[2] = TextToCode[province][city][area].code;
          }
        },
        deep: true
      }
    },
    mounted () {
      this.init();
    },
    methods: {
      init () {
        this.$http.get("tables").then((response) => {
          this.operateOptionList = response.data;
        });
      },
      queryoperateOptionList (query) {
        if (query !== '') {
          this.loading = true;
          this.$http.get("tables" + "?tablename=" + query).then((response) => {
            this.loading = false;
            this.operateOptionList = response.data;
          });
        } else {
          this.options = [];
        }
      },
      beforerouteUpload (file) {
        const image = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/gif';
        if (!image) {
          this.$message.error('只支持 jpg/jpeg/png/gif 格式!');
        }
        let isLtSize = false;
        isLtSize = file.size / 1024 / 1024 < 5;
        if (!isLtSize) {
          this.$message.error('最大支持 5MB!');
        }
        return image && isLtSize;
      },
      handlerouteSuccess (response, file, fileList) {
        let filesData = [];
        fileList.forEach(function (item, index) {
          if (item.url) {
            filesData.push({
              'name': item.name,
              'url': item.url
            });
          } else {
            if (response.data) {
              filesData.push({
                'name': item.name,
                'url': response.data
              });
            }
          }
        });
        this.formFieldsData.route = JSON.stringify(filesData);
        this.routefileList = fileList;
      },
      handlerouteExceed (files, fileList) {
        this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      submitrouteUpload () {
        this.$refs.routeupload.submit();
      },
      handlerouteRemove (file, fileList) {
        let filesData = [];
        fileList.forEach(function (item, index) {
          if (item.url) {
            filesData.push({
              'name': item.name,
              'url': item.url
            });
          }
        });
        this.formFieldsData.route = JSON.stringify(filesData);
      },
      beforeparamsUpload (file) {
        const image = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/gif';
        if (!image) {
          this.$message.error('只支持 jpg/jpeg/png/gif 格式!');
        }
        let isLtSize = false;
        isLtSize = file.size / 1024 / 1024 < 5;
        if (!isLtSize) {
          this.$message.error('最大支持 5MB!');
        }
        return image && isLtSize;
      },
      handleparamsSuccess (response, file, fileList) {
        let filesData = [];
        fileList.forEach(function (item, index) {
          if (item.url) {
            filesData.push({
              'name': item.name,
              'url': item.url
            });
          } else {
            if (response.data) {
              filesData.push({
                'name': item.name,
                'url': response.data
              });
            }
          }
        });
        this.formFieldsData.params = JSON.stringify(filesData);
        this.paramsfileList = fileList;
      },
      handleparamsExceed (files, fileList) {
        this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      submitparamsUpload () {
        this.$refs.paramsupload.submit();
      },
      handleparamsRemove (file, fileList) {
        let filesData = [];
        fileList.forEach(function (item, index) {
          if (item.url) {
            filesData.push({
              'name': item.name,
              'url': item.url
            });
          }
        });
        this.formFieldsData.params = JSON.stringify(filesData);
      },
      handleoperateChange (value) {
        let region = '';
        value.forEach(item => {
          if(region){
            region = region + ',' + CodeToText[item];
          }else{
            region = CodeToText[item];
          }
        });
        this.formFieldsData.operate = region;
      }
    }
  };
</script>
